package com.hgx.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.google.gson.Gson;

public class HStringUtil {

	private static Gson gson=new Gson();//gson类
	/**
	 * 防代理 取真实IP
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if (ip.equals("127.0.0.1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ip = inet.getHostAddress();
			}
		}

		if (ip != null && ip.length() > 15) { // "***.***.***.***".length() = 15
			if (ip.indexOf(",") > 0) {
				System.out.println(ip);
				ip = ip.substring(0, ip.indexOf(","));
			}
		}
		return ip;
	}

	/**
	 * 获取项目名称
	 * 
	 * @return
	 */
	public static String getContentPath() {
		String s = Thread.currentThread().getContextClassLoader().getResource(
				"/").getPath();
		s = s.substring(0, s.indexOf("/WEB-INF")).replace("/WEB-INF", "");
		s = s.substring(s.lastIndexOf("/") + 1, s.length());
		System.out.println(s);
		return s;
	}

	/**
	 * null ture not null false
	 * 
	 * @param o
	 * @return
	 */
	public static boolean isnull(Object o) {
		if (o == null || "".equals(o.toString().trim())) {
			return true;
		} else {
			return false;
		}
	}

	/***
	 * 判断当前字符串的编码格式 传入 String
	 * 
	 */
	public static String getStringCode(String str) {
		String encode = "GB2312";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s = encode;
				return s;
			}
		} catch (Exception exception) {
		}
		encode = "ISO-8859-1";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s1 = encode;
				return s1;
			}
		} catch (Exception exception1) {
		}
		encode = "UTF-8";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s2 = encode;
				return s2;
			}
		} catch (Exception exception2) {
		}
		encode = "GBK";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s3 = encode;
				return s3;
			}
		} catch (Exception exception3) {
		}
		return null;
	}
	public static String getStringCode() {
		String str="寻找字符集ABCD123abcd";
		//System.out.println("zfj"+getStringCode(str));
		return getStringCode(str);
	}
	public static String OtherToUTF8(String str) throws UnsupportedEncodingException{
		String encode=getStringCode(str);
		if(isnull(encode)){
			return str;
		}
		return new String(new String(str.getBytes(encode),encode).getBytes("utf-8"),"utf-8");
	}
	public static String  UFT8ToGBK(String str) throws UnsupportedEncodingException{
		return new String(new String(str.getBytes("gbk"),"gbk").getBytes("utf-8"),"utf-8");
	}
	public static String  UFT8ToGB2312(String str) throws UnsupportedEncodingException{
		return new String(new String(str.getBytes("gbk"),"gbk").getBytes("utf-8"),"utf-8");
	}
	public static String UTF8ToStringEncode(String str) throws UnsupportedEncodingException{
		return new String(new String(str.getBytes(getStringCode()),getStringCode()).getBytes("utf-8"),"utf-8");
	}
	/*
	 * 获取jvm编码
	 * */
	
	 public static String getJVMEnconding() {  
		 //System.out.println(Charset.defaultCharset().toString());
	        return Charset.defaultCharset().toString();  
	      }  
	 /**
	  * 转义 sql
	 * @return 
	  * 
	  */
	 /*
	 public  static String StrToSql(String s){
		 return StringEscapeUtils.escapeSql(s);
	 }*/

	/**
	 * 字符串函数  模仿数据库 REGIHT()
	 * @param value
	 * @param count
	 * @return
	 */
	public static String right(String value,Integer count){
		
		return value.substring(value.length()-count);
	}
	/**
	 * 字符串函数  模仿数据库 LEFT()
	 * @param value
	 * @param count
	 * @return
	 */
	public static String left(String value,Integer count){
		return value.substring(0,count);
	}
	
	/**
	 * 判断该字符串是不是一个数字 是返回true 否返回false
	 * 
	 * @param str
	 * @author hejunxin 2015-6-19 15:25:28
	 * @return
	 */
	public static boolean isNum(String str) {
		String check = "^\\d+\\.?\\d*$";
		Pattern regex = Pattern.compile(check);
		Matcher matcher = regex.matcher(str);
		return matcher.matches();
	}
	
	/**
	 * 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为2,英文字符长度为1
	 * 
	 * @param String s 需要得到长度的字符串
	 * @return int 得到的字符串长度
	 * @author hejunxin 2015-6-19 15:26:36
	 */
	public static int length(String s) {
		if (s == null)
			return 0;
		char[] c = s.toCharArray();
		int len = 0;
		for (int i = 0; i < c.length; i++) {
			len++;
			if (!isLetter(c[i])) {
				len++;
			}
		}
		return len;
	}
	
	/**
	 * 汉字编码区别于其他编码的标志就是汉字编码的最高位是1. 0x80在计算机内部表示为1000 0000
	 * 这段程序常用于判断当前字符是否是汉字.&是按位与, 对应都是1时才为1, 其它情况均未0. 如: 1010 1011 & 1000 0000 =
	 * 1000 0000
	 * @param c
	 * @return
	 */
	public static boolean isLetter(char c) {
		int k = 0x80;
		return c / k == 0 ? true : false;
	}
	
	/**
	 * 根据文件路径得到文件里的内容
	 * @param filepath
	 * @return
	 */
	public static String readTextByFile(String filepath,String encode){
		
		StringBuffer sbStr = new StringBuffer();
		
		File file = new File(filepath);
		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(file),encode);
			BufferedReader ins = new BufferedReader(read);
			String dataLine = "";
			while(null!=(dataLine=ins.readLine())){
				sbStr.append(dataLine);
			}
			
			ins.close();
			
		} catch (FileNotFoundException e) {
			System.out.println("=======文件不存在=======");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return sbStr.toString();
	}
	
	/**
	 * 转译HTML敏感词
	 * @param content
	 * @return
	 */
	public static String htmlToStr(String content) {
		 if(content==null) return "";        
		     String html = content;
		      
		     html = html.replace( "'", "&apos;");
		//   html = html.replaceAll( "&", "&amp;");
		//   html = html.replace( " ", "&nbsp;");// 替换空格
		     html = html.replace( "\"", "&quot;");  //"
		     html = html.replace( "\t", "&nbsp;&nbsp;");// 替换跳格
		     html = html.replace("<", "&lt;");
		  
		     html = html.replaceAll( ">", "&gt;");
		    
		     return html;
	}
	
	/**
	 * 将String转换为HTML内容
	 * @param content
	 * @return
	 */
	public static String StrToHtml(String content) {
		 if(content==null) return "";        
		     String html = content;
		      
		     html = html.replace( "&apos;", "'");
		     html = html.replace( "&#39;", "'");
		//   html = html.replaceAll( "&", "&amp;");
		//   html = html.replace( " ", "&nbsp;");// 替换空格
		     html = html.replace( "&quot;", "\"");  //"
		     html = html.replace( "&nbsp;&nbsp;", "\t");// 替换跳格
		     html = html.replace("&lt;", "<");
		     html = html.replaceAll( "&gt;", ">");
		    
		     return html;
	}
	
	/**
	 * 去掉所有HTML元素
	 * @param input
	 * @return
	 */
    public static String splitAndFilterString(String input) {        
        if (input == null || input.trim().equals("")) {        
            return "";        
        }        
        // 去掉所有html元素,        
        String str = input.replaceAll("//&[a-zA-Z]{1,10};", "").replaceAll(        
                "<[^>]*>", "");        
        str = str.replaceAll("[(/>)<]", "");        
        return str;        
    }
	
    /**
     * 将字符串转换为标签字符串
     * @param str
     * @return
     *//*
	public static String convertSpecialStr(String str) {
		if(isnull(str)) {
			return str;
		}
		return StrToSql(str.replace("<", "&lt;").replace(">", "&gt;").replace("'", "&#39;").replace("\\\"", "&quot;"));
	}
	*/
	/**
	 * 将html标签字符串转换为正常字符串
	 * @param str
	 * @return
	 */
	/*public static String convertStrSpecial(String str) {
		if(isnull(str)) {
			return str;
		}
		return StrToSql(str.replace("&lt;", "<").replace("&gt;", ">").replace("&#39;", "'").replace("&quot;", "\\\""));
	}*/
}
